Session tracking with JSP
HTTP is a stateless protocol; a separate connection with the server computer is established each time a client opens a Webpage. The web server automatically does not maintain record of any previous client request. That is server will have no idea if the client has already visited it or not. Different methods can be used to maintain the session between web client and the web server such that server computer can remember the client:
Sometimes it becomes necessary to restrict users from accessing some webpages without authorization; Those pages can be accessed only after users logs into the system successfully.
For example, we can't access contains of the email account even we know the URL of those email account pages, we must first log into the email system to access those contents. If we type the URL of inbox page, without logging, we will be taken to login form. To disable users from accessing web pages without logging, we can use the concept of session. Here three simple pages are created:
User can't access adminpanel.jsp page without login to the system. Even users type URL of adminpanel.jsp without logging s/he is taken to login form. If user logins successfully then only adminpanel.jsp page is displayed.
At the beginning of the adminpanel.jsp page, if session variable is set or not is checked. If session is set then contents of the adminpanel.jsp is displayed otherwise user will be redirected to the loginform.html page.
When user submits username and password through the loginform.html, the submitted username and password is compared with the specified values (we can extract data from database and compare username and password also); if the values match then a session variable is set and user is redirected to the adminpanel.jsp otherwise user is redirected to the loginform.html.
<html> <body> <form method='post' action='checklogin.jsp'> <p><input type='text' name='uname'></p> <p><input type='text' name='password'></p> <p><input type='submit' name='submit'></p> </form> </body> </html>
<% String uname = request.getParameter("uname"); String pass = request.getParameter("password"); if(uname.equals("batman") && pass.equals("bat%man")){ session.setAttribute("key","batman"); response.sendRedirect("adminpanel.jsp"); }else{ out.print("<br>Uname: "+uname+"<br>Password: "+pass); response.sendRedirect("loginform.html"); } %>
<% if(session.getAttribute("key")== "" && session.getAttribute("key").equals("batman")==false){ response.sendRedirect("loginform.html"); } %> <html> <body> <div> <a href="logout.jsp">Logout</a> </div> <div> Add </div> <div> Edit </div> <div> Delete </div> <div> Save </div> </body> </html>
<% session.setAttribute("key",""); response.sendRedirect("loginform.html"); %>